package com.gitee.wsl.data.store.db

import android.app.Application
import android.database.Cursor
import androidx.room.Room
import androidx.room.RoomDatabase

fun createRoomDatabase(app: Application): RoomDatabase.Builder<KVStoreDatabase> {
    val dbFile = app.getDatabasePath(DB_KVStore_NAME)

    return Room.databaseBuilder<KVStoreDatabase>(
            context = app,
            name = dbFile.absolutePath,
        ).enableMultiInstanceInvalidation()
}



internal inline fun Cursor.forEachRow(block: (Cursor) -> Unit) {
    if (moveToFirst()) {
        do {
            block(this)
        } while (moveToNext())
    }
}

internal inline fun <T> Cursor.mapAndClose(mapper: (Cursor) -> T): List<T> =
    use {
        val result = ArrayList<T>(count)
        forEachRow {
            result.add(mapper(it))
        }
        result
    }

internal fun Cursor.getBoolean(columnIndex: Int) = getInt(columnIndex) != 0
